<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  label-width="70px">
      <el-row>
        <el-form-item label="客户名称" prop="khname">
          <el-input
            v-model="queryParams.khname"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="报价单号" prop="bjdh">
          <el-input
            v-model="queryParams.bjdh"
            placeholder="请输入报价单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="完工单号" prop="wgdh">
          <el-input
            v-model="queryParams.wgdh"
            placeholder="请输入完工单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="下场日期">
          <el-date-picker
            v-model="querySj"
            @change="selectTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完工日期">
          <el-date-picker
            v-model="queryWgSj"
            @change="selectWgTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="bz">
          <el-input
            v-model="queryParams.bz"
            placeholder="请输入备注"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="报价单">
          <el-checkbox-group v-model="ywdWs" size="mini" @change="selectWszt">
            <el-checkbox border label="ws">完善</el-checkbox>
            <el-checkbox border label="dws">待完善</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="完工单">
          <el-checkbox-group v-model="wgdWs" size="mini" @change="selectWgdzt">
            <el-checkbox border label="ws">完善</el-checkbox>
            <el-checkbox border label="dlr">待录入</el-checkbox>
            <el-checkbox border label="dws">待完善</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="是否回款">
          <el-checkbox-group v-model="sfhk" size="mini" @change="selectSfhk">
            <el-checkbox border v-for="item in hkList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="录单日期">
          <el-checkbox-group v-model="rq" size="mini" @change="selectRq">
            <el-checkbox label="zt" border>昨天</el-checkbox>
            <el-checkbox label="jt" border>今天</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="下场状态">
          <el-checkbox-group v-model="xczt" size="mini" @change="selectXczt">
            <el-checkbox border v-for="item in xcList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>

      <el-row v-show="showSearch">
        <el-form-item label="开票日期" prop="kprq">
          <el-date-picker
            v-model="kpsjSj"
            @change="selectKpTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回款日期" prop="kprq">
          <el-date-picker
            v-model="hkSj"
            @change="selectHkTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同金额" prop="htje">
          <el-input
            v-model="queryParams.htje"
            placeholder="请输入合同金额"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="证件份数" prop="zjfs">
          <el-input
            v-model="queryParams.zjfs"
            placeholder="请输入证件份数"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="开票金额" prop="kpje">
          <el-input
            v-model="queryParams.kpje"
            placeholder="请输入开票金额"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属公司">
          <el-checkbox-group v-model="ssgs" size="mini" @change="selectSsgs">
            <el-checkbox border v-for="item in ssgsList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="特殊处理">
          <el-checkbox-group v-model="tscl" size="mini" @change="selectTscl">
            <el-checkbox border v-for="item in tsclList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="申请电子档" label-width="90px">
          <el-checkbox-group v-model="sqdzd" size="mini" @change="selectSqdzd">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="电子档是否给客户" label-width="125px">
          <el-checkbox-group v-model="dzdsfgkh" size="mini" @change="selectDzdsfgkh">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="纸质打印">
          <el-checkbox-group v-model="zzdy" size="mini" @change="selectZzdy">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="已邮寄客户" label-width="90px">
          <el-checkbox-group v-model="yyjkh" size="mini" @change="selectYyjkh">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="用户确认完工单" label-width="125px">
          <el-checkbox-group v-model="yhsfqr" size="mini" @change="selectYhsfqr">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否开票" label-width="90px">
          <el-checkbox-group v-model="sfkp" size="mini" @change="selectSfkp">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="下场通知用户" label-width="125px">
          <el-checkbox-group v-model="xctzyh" size="mini" @change="selectXctzyh">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-d-caret" size="mini" @click="showSearch=!showSearch">{{showSearch ? "隐藏" : "展开"}}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button v-if="false" icon="el-icon-refresh" size="mini" @click="resetData">清洗数据</el-button>
        </el-form-item>
      </el-row>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:ywdwgd:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gd:ywdwgd:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gd:ywdwgd:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:ywdwgd:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleSelectExport"
          v-hasPermi="['gd:ywd:export']"
        >导出选择数据</el-button>
      </el-col>
      <!-- 批量处理 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          :disabled="multiple"
          @click="batchHandle"
        >批量处理</el-button>
      </el-col>
      <!-- 制单中心 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="showMake = true"
        >制单中心</el-button>
      </el-col>
      <!-- 开发票 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="handleSelectKfp"
        >开发票</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ywdwgdList" @selection-change="handleSelectionChange" @sort-change="sortChange">
      <el-table-column fixed sortable type="selection" width="55" align="center" />
      <el-table-column fixed sortable label="报价单号" width="120px" align="left" prop="bjdh">
        <template slot-scope="scope">
          <div style="color: #00afff;cursor: pointer;">
            <span @click="showInfo(scope.row)"> {{scope.row.bjdh}}</span>
            <el-link :underline="false" type="success" @click="copyText(scope.row.bjdh)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed sortable label="完工单号" width="115px" align="left" prop="wgdh">
        <template slot-scope="scope">
          <div style="color: #00afff;cursor: pointer;">
            <span @click="showInfo(scope.row)"> {{scope.row.wgdh}}</span>
            <el-link :underline="false" type="success" @click="copyText(scope.row.wgdh)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed sortable label="客户名称" width="200px" align="left" prop="khname">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.ssgs === 'szzb'" style="color: #F56C6C"> {{scope.row.khname}}</span>
            <span v-else> {{scope.row.khname}}</span>
            <el-link :underline="false" type="success" @click="copyText(scope.row.khname)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable label="检测方式" align="center" width="100px" prop="jcfs">
        <template slot-scope="scope">
          <span v-if="scope.row.jcfs==='2'">送检</span>
          <span v-else>下场</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="下场状态" align="center" width="100px" prop="xczt">
        <template slot-scope="scope">
          <span>{{xcList.filter(item => item.dictValue === scope.row.xczt)[0] !== undefined ? xcList.filter(item => item.dictValue === scope.row.xczt)[0].dictLabel : ""}}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="是否回款" align="center" width="100px" prop="sfhk">
        <template slot-scope="scope">
          <span v-if="scope.row.sfhk==='1'"><el-tag type="success">是</el-tag></span>
          <span v-else-if="scope.row.sfhk==='2'"><el-tag type="warning">部分回款</el-tag></span>
          <span v-else-if="scope.row.sfhk==='3'"><el-tag type="warning">否</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column sortable label="回款金额" align="center" width="100px" prop="hkje" />
      <el-table-column sortable label="回款日期" align="center" width="100px" prop="hkrq">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.hkrq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报价单" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag @click="showInfo(scope.row)" v-if="scope.row.bjdfj !== '' && scope.row.bjdfj !== null && scope.row.bjdfj !== undefined" type="success">完善</el-tag>
          <el-tag @click="showInfo(scope.row)" v-else type="warning">待完善</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="完工单" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag v-if="(scope.row.wgdh !== '' && scope.row.wgdh !== null&& scope.row.wgdh !== undefined)
                        && (scope.row.wgdfj !== '' && scope.row.wgdfj !== null&& scope.row.wgdfj !== undefined)"
                  @click="showInfo(scope.row)" type="success">完善</el-tag>
          <el-tooltip content="点击完善" placement="right" effect="light">\
            <el-tag
              v-if="(scope.row.wgdh !== '' && scope.row.wgdh !== null && scope.row.wgdh !== undefined)
                        && (scope.row.wgdfj === '' || scope.row.wgdfj === null || scope.row.wgdfj === undefined)"
              style="cursor: pointer"
              type="warning"
              @click="showInfo(scope.row)"
              >待完善</el-tag>
          </el-tooltip>
          <el-tooltip content="点击完善" placement="right" effect="light">
            <el-tag
              v-if="(scope.row.wgdh === '' || scope.row.wgdh === null || scope.row.wgdh === undefined)"
              style="cursor: pointer"
              type="warning"
              @click="showInfo(scope.row)"
              >待录入</el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column sortable label="下场日期" align="center" prop="xcrq" width="100px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.xcrq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="开票日期" align="center" prop="kprq" width="100px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.kprq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="备注" align="center" prop="bz">
        <template slot-scope="scope">
          <span style="color: #F56C6C">{{ scope.row.bz}}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="scBjd(scope.row)"
          >生成报价单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showInfo(scope.row)"
            v-hasPermi="['gd:ywdwgd:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:ywdwgd:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <formInfo v-if="open" :open="open" :title="title" :form-info="form" :type="type" @closeForm="cancel"></formInfo>

    <el-dialog title="生成报价单" :visible.sync="showGenBjd" @close="cancelBjd" width="70%" append-to-body>
      <el-form ref="bjdForm" :model="bjdForm" :rules="rulesBjd" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="报价日期" prop="bjrq">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="bjdForm.bjrq"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择报价日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="330px" label="生成的报价单编号是出厂编号 还是 管理编号数据"></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="编号" prop="bjbh">
              <el-radio v-model="bjdForm.bjbh" label="ccbh" border size="medium">出厂编号</el-radio>
              <el-radio v-model="bjdForm.bjbh" label="glbh" border size="medium">管理编号</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="shengChengBjd">确 定</el-button>
        <el-button type="primary" @click="queryLsBjd">查看历史报价单</el-button>
        <el-button @click="cancelBjd">取 消</el-button>
      </div>

      <el-dialog title="生成历史报价单" :visible.sync="showLsBjd" @close="cancelLsbjd" width="60%" append-to-body>
        <el-table
          border
          :data="lsFjList">
          <el-table-column
            prop="fjname"
            header-align="center"
            label="报价单名称">
          </el-table-column>
          <el-table-column
            width="110"
            prop="createTime"
            header-align="center"
            label="生成日期">
          </el-table-column>
          <el-table-column
            width="280"
            header-align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button
                @click="downFile(scope.row)"
                type="primary"
                icon="el-icon-download"
                size="mini"
              >下载</el-button>
              <el-button
                @click="scBjdData(scope.row)"
                type="info"
                icon="el-icon-download"
                size="mini"
              >提取报价单数据</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

    </el-dialog>

    <batchHandle v-if="showHandle" :showHandle="showHandle" :ids="ids" :ywdwgdList="ywdwgdList" @cancelHandle="cancelHandle"></batchHandle>

    <makeCenter v-if="showMake" :showMake="showMake" @closeMake="showMake = false"></makeCenter>

  </div>
</template>

<script>
import { listYwdwgd, getYwdwgd, delYwdwgd, addYwdwgd, updateYwdwgd, resetDatabase, handleZt, genBjd, genBjdData, handleKfp } from '@/api/gd/ywdwgd'
import formInfo from "./formInfo.vue"
import batchHandle from "./batchHandle.vue"
import makeCenter from "./makeCenter.vue"
import { allListFj, getFjById } from '@/api/gd/fj'
export default {
  name: "Ywdwgd",
  components: { formInfo, batchHandle, makeCenter },
  data() {
    return {
      showMake: false,
      showHandle: false,
      rulesBjd: {
        bjrq: [
          { required: true, message: "请选择报价日期", trigger: "blur" }
        ],
        bjbh: [
          { required: true, message: "请选择编号", trigger: "blur" }
        ]
      },
      lsFjList: [],
      showLsBjd: false,
      buttonLoading: false,
      bjdForm: {},
      showGenBjd: false,
      showForm: false,
      querySj: [],
      queryWgSj: [],
      ywdWs: [],
      wgdWs: [],
      sfhk: [],
      rq: [],
      xczt: [],
      ssgs: [],
      tscl: [],
      sqdzd: [],
      dzdsfgkh: [],
      zzdy: [],
      yyjkh: [],
      yhsfqr: [],
      sfkp: [],
      xctzyh: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 业务完工单表格数据
      ywdwgdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      type: 1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bjdh: undefined,
        khid: undefined,
        khname: undefined,
        bjdfj: undefined,
        bjdfjpdf: undefined,
        htje: undefined,
        khsh: undefined,
        wgdh: undefined,
        wgrq: undefined,
        zjfs: undefined,
        wgdfj: undefined,
        wgdfjpdf: undefined,
        xcrq: undefined,
        xcfzr: undefined,
        xcfzrname: undefined,
        xcry: undefined,
        xclx: undefined,
        sfsqdzd: undefined,
        sfgkhdzd: undefined,
        zzdy: undefined,
        yyjkh: undefined,
        sfkp: undefined,
        kpje: undefined,
        fph: undefined,
        kprq: undefined,
        tscl: undefined,
        wbqk: undefined,
        sfhk: undefined,
        hkje: undefined,
        hkrq: undefined,
        dzzh: undefined,
        ssgs: undefined,
        bz: undefined,
        params: {},
        orderByCode: ''
      },
      sfList: [],
      xcList: [],
      hkList: [],
      sjztList: [],
      dzzhList: [],
      tsclList: [],
      ssgsList: [],
      kpsjSj: [],
      hkSj: [],
      ShowBtn: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      form: {},
      bjdFjList: [],
      wgdFjList: [],
      sy: false
    };
  },
  created() {
    if (!this.sy) {
      this.getList();
    }
    this.getDict();
  },
  watch: {
    '$route': {
      immediate: true,
      async handler(route) {
        if (route.query.sy === "true") {
          await this.resetQueryParam()
          switch (route.query.type) {
            case "dlrwgdjt":  // 录入今天
              await this.handleData(route.query.type)
              this.queryParams.wgdWszt = "dlr"
              this.wgdWs.push("dlr")
              break
            case "dwswgdjt":  // 待完善今天
              await this.handleData(route.query.type)
              this.queryParams.wgdWszt = "dws"
              this.wgdWs.push("dws")
              break
            case "dlrwgdzdy":  // 待录入完工单自定义
              await this.handleData(route.query.type)
              this.queryParams.wgdWszt = "dlr"
              this.wgdWs.push("dlr")
              break
            case "dwswgdzdy":  // 待完善完工单自定义
              await this.handleData(route.query.type)
              this.queryParams.wgdWszt = "dws"
              this.wgdWs.push("dws")
              break
            case "yhyqr":  // 用户是否确认
              this.queryParams.wgdfj = 'isNull'
              break
            case "wkfp":  // 未开发票
              this.queryParams.sfkp = '0'
              break
            case "whk":  // 未回款
              this.queryParams.sfhk = '3'
              break
            case "xctzyh":  // 下场通知用户
              this.queryParams.xctzyh = '0'
              break
            case "dsqdzzs":  // 待申请电子证书
              this.queryParams.sfsqdzd = '0'
              break
            case "dzdwfkh":  // 电子单未发送给客户
              this.queryParams.sfgkhdzd = '0'
              break
            case "ddyzzzs":  // 待打印纸质证书
              this.queryParams.zzdy = '0'
              break
            case "dyj":  // 待邮寄
              this.queryParams.yyjkh = '0'
              break
          }
          this.queryParams.pageSize = 10
          this.sy = true
          this.getList()
        }
      },
      deep: true
    },
  },
  methods: {
    sortChange({ column, prop, order }) {
      switch (prop) {
        case 'bjdh':
          this.queryParams.orderByCode = order === 'ascending' ? 'bjdh,asc' : 'bjdh,desc'
          break
        case 'wgdh':
          this.queryParams.orderByCode = order === 'ascending' ? 'wgdh,asc' : 'wgdh,desc'
          break
        case 'khname':
          this.queryParams.orderByCode = order === 'ascending' ? 'khname,asc' : 'khname,desc'
          break
        case 'jcfs':
          this.queryParams.orderByCode = order === 'ascending' ? 'jcfs,asc' : 'jcfs,desc'
          break
        case 'xczt':
          this.queryParams.orderByCode = order === 'ascending' ? 'xczt,asc' : 'xczt,desc'
          break
        case 'sfhk':
          this.queryParams.orderByCode = order === 'ascending' ? 'sfhk,asc' : 'sfhk,desc'
          break
        case 'hkje':
          this.queryParams.orderByCode = order === 'ascending' ? 'hkje,asc' : 'hkje,desc'
          break
        case 'hkrq':
          this.queryParams.orderByCode = order === 'ascending' ? 'hkrq,asc' : 'hkrq,desc'
          break
        case 'xcrq':
          this.queryParams.orderByCode = order === 'ascending' ? 'xcrq,asc' : 'xcrq,desc'
          break
        case 'kprq':
          this.queryParams.orderByCode = order === 'ascending' ? 'kprq,asc' : 'kprq,desc'
          break
        case 'bz':
          this.queryParams.orderByCode = order === 'ascending' ? 'bz,asc' : 'bz,desc'
          break
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    batchHandle() {
      this.showHandle = true
    },
    cancelHandle() {
      this.showHandle = false
      this.getList()
    },
    scBjdData(row) {
      delete row.createTime
      genBjdData(row, 'blob').then(res => {
        if (res !== null) {
          const binaryData = [];
          binaryData.push(res);
          let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
          const link = document.createElement('a');
          link.href = url
          link.download = "报价单" + this.getTodayDate() + ".xlsx";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      })
    },
    downFile(file) {
      // 调用删除附件功能，将附件进行删除
      getFjById(file.fjid, 'blob').then(response => {
        const binaryData = [];
        binaryData.push(response);
        let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
        const link = document.createElement('a');
        link.href = url
        link.download = file.fjname;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },
    cancelLsbjd() {
      this.lsFjList = []
      this.showLsBjd = false
    },
    shengChengBjd() {
      // this.buttonLoading = true
      this.$refs['bjdForm'].validate((valid) => {
        if (valid) {
          genBjd(this.bjdForm).then(res => {
            this.cancelBjd()
            if (res.data !== null && res.data !== undefined && res.data !== "") {
              let obj = res.data
              getFjById(obj.fjid, 'blob').then(response => {
                const binaryData = [];
                binaryData.push(response);
                let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
                const link = document.createElement('a');
                link.href = url
                link.download = obj.fjname;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
              })
            }
          })
        }
      });
    },
    // 查看历史报价单
    queryLsBjd() {
      if (this.bjdForm.lsbjdid !== '' && this.bjdForm.lsbjdid !== null && this.bjdForm.lsbjdid !== undefined) {
        // 查询附件列表
        allListFj(this.bjdForm.lsbjdid).then(res => {
          this.lsFjList = res
          this.showLsBjd = true
        })
      }else {
        this.$message.error("当前未生成报价单，请先生成报价单")
      }
    },
    async handleData(type) {
      const now = new Date();
      // 判断是今天还是自定义
      if (type === 'dlrwgdjt' || type === 'dwswgdjt') {
        // 当前年的1号0点
        const year = now.getFullYear();
        const firstDayOfYear = new Date(year, 0, 1, 0, 0, 0, 0);
        let startTime = this.formatDateTime(firstDayOfYear);
        // 设置时间为今天的 23 点 59 分 59 秒
        const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const endOfDay = new Date(startOfDay);
        endOfDay.setHours(23, 59, 59, 999);
        let endTime = this.formatDateTime(endOfDay);
        this.queryParams.params.startXcrq = startTime
        this.queryParams.params.endXcrq = endTime
        this.$set(this.querySj, 0 , startTime)
        this.$set(this.querySj, 1 , endTime)
      }else if (type === 'dlrwgdzdy' || type === 'dwswgdzdy') {
        const year = now.getFullYear();
        // 当前年的1号0点
        const firstDayOfYear = new Date(year, 0, 1, 0, 0, 0, 0);
        let startTime = this.formatDateTime(firstDayOfYear);
        // 当前时间三天前的时间23:59:59
        let dayNum = 3
        await this.getConfigKey("sy_dzwgdcx").then(async res => {
          dayNum = res.msg
        })
        const threeDaysAgo = new Date(now.getTime() - (dayNum * 24 * 60 * 60 * 1000));
        threeDaysAgo.setHours(23, 59, 59, 999);
        let endTime = this.formatDateTime(threeDaysAgo);
        this.queryParams.params.startXcrq = startTime
        this.queryParams.params.endXcrq = endTime
        this.$set(this.querySj, 0 , startTime)
        this.$set(this.querySj, 1 , endTime)
      }
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return `${year}-${month}-${day}`;
    },
    selectXczt(val) {
      this.queryParams.xczt = val.toString()
      this.getList()
    },
    selectWszt(val) {
      this.queryParams.bjdWszt = val.toString()
      this.getList()
    },
    selectWgdzt(val) {
      this.queryParams.wgdWszt = val.toString()
      this.getList()
    },
    selectSfhk(val) {
      this.queryParams.sfhk = val.toString()
      this.getList()
    },
    selectSsgs(val) {
      this.queryParams.ssgs = val.toString()
      this.getList()
    },
    selectTscl(val) {
      this.queryParams.tscl = val.toString()
      this.getList()
    },
    selectSqdzd(val) {
      this.queryParams.sfsqdzd = val.toString()
      this.getList()
    },
    selectDzdsfgkh(val) {
      this.queryParams.sfgkhdzd = val.toString()
      this.getList()
    },
    selectZzdy(val) {
      this.queryParams.zzdy = val.toString()
      this.getList()
    },
    selectYyjkh(val) {
      this.queryParams.yyjkh = val.toString()
      this.getList()
    },
    selectYhsfqr(val) {
      this.queryParams.yhsfqr = val.toString()
      this.getList()
    },
    selectSfkp(val) {
      this.queryParams.sfkp = val.toString()
      this.getList()
    },
    selectXctzyh(val) {
      this.queryParams.xctzyh = val.toString()
      this.getList()
    },
    selectTime(time) {
      if(time !== null) {
        this.queryParams.params.startXcrq = time[0]
        this.queryParams.params.endXcrq = time[1]
      }
    },
    selectWgTime(time) {
      this.queryParams.params.startWgrq = time[0]
      this.queryParams.params.endWgrq = time[1]
    },
    selectKpTime(time) {
      this.queryParams.params.startKprq = time[0]
      this.queryParams.params.endKprq = time[1]
    },
    selectHkTime(time) {
      this.queryParams.params.startHkrq = time[0]
      this.queryParams.params.endHkrq = time[1]
    },
    scBjd(row) {
      if (row.wgdfj !== '' && row.wgdfj !== undefined && row.wgdfj !== null) {
        this.$set(this, 'bjdForm', row)
        this.$set(this.bjdForm, 'bjrq', new Date())
        // this.bjdForm = row
        this.showGenBjd = true
      }else {
        this.$message.error("请先上传完工单附件！")
      }
    },
    async showInfo(row) {
      // 展示详情
      this.open = true
      this.type = 2
      this.form = row
      this.title = "业务单信息";
    },
    getDict() {
      this.getDicts("gd_sf").then(res => {
        this.sfList = res.data
      })
      // 是否已下场
      this.getDicts("gd_xczt_xbb").then(res => {
        this.xcList = res.data
      })
      // 是否回款
      this.getDicts("gd_sfhk").then(res => {
        this.hkList = res.data
      })
      // 送检状态
      this.getDicts("gd_sjzt").then(res => {
        this.sjztList = res.data
      })
      // 到账账号
      this.getDicts("gd_dzzh").then(res => {
        this.dzzhList = res.data
      })
      // 特殊处理
      this.getDicts("gd_tscl").then(res => {
        this.tsclList = res.data
      })
      // 特殊处理
      this.getDicts("gd_ssgs").then(res => {
        this.ssgsList = res.data
      })
    },
    /** 查询业务完工单列表 */
    getList() {
      this.loading = true;
      listYwdwgd(this.queryParams).then(response => {
        this.ywdwgdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancelBjd() {
      this.showGenBjd = false
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.bjdFjList = []
      this.wgdFjList = []
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        bjdh: undefined,
        khid: undefined,
        khname: undefined,
        bjdfj: undefined,
        bjdfjpdf: undefined,
        htje: undefined,
        khsh: undefined,
        wgdh: undefined,
        wgrq: undefined,
        zjfs: undefined,
        wgdfj: undefined,
        wgdfjpdf: undefined,
        xcrq: undefined,
        xcfzr: undefined,
        xcfzrname: undefined,
        xcry: undefined,
        xczt: "1",
        xclx: "10",
        sfsqdzd: "0",
        sfgkhdzd: "0",
        zzdy: "0",
        yyjkh: "0",
        sfkp: "0",
        kpje: undefined,
        fph: undefined,
        kprq: undefined,
        tscl: "0",
        wbqk: "0",
        sfhk: "3",
        hkje: undefined,
        hkrq: undefined,
        dzzh: "1",
        ssgs: "tjfgs",
        jcfs: "1",
        bjrq: new Date(),
        xctzyh: "0",
        bz: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        bjdh: undefined,
        khid: undefined,
        khname: undefined,
        bjdfj: undefined,
        bjdfjpdf: undefined,
        htje: undefined,
        khsh: undefined,
        wgdh: undefined,
        wgrq: undefined,
        zjfs: undefined,
        wgdfj: undefined,
        wgdfjpdf: undefined,
        xcrq: undefined,
        xcfzr: undefined,
        xcfzrname: undefined,
        xcry: undefined,
        xclx: undefined,
        sfsqdzd: undefined,
        sfgkhdzd: undefined,
        zzdy: undefined,
        yyjkh: undefined,
        sfkp: undefined,
        kpje: undefined,
        fph: undefined,
        kprq: undefined,
        tscl: undefined,
        wbqk: undefined,
        sfhk: undefined,
        hkje: undefined,
        hkrq: undefined,
        dzzh: undefined,
        ssgs: undefined,
        bz: undefined,
        params: {},
        orderByCode: undefined
      }
      this.querySj = []
      this.queryWgSj = []
      this.ywdWs = []
      this.wgdWs = []
      this.sfhk = []
      this.rq = []
      this.xczt = []
      this.ssgs = []
      this.tscl = []
      this.sqdzd = []
      this.dzdsfgkh = []
      this.zzdy = []
      this.yyjkh = []
      this.yhsfqr = []
      this.sfkp = []
      this.xctzyh = []
      this.kpsjSj = []
      this.hkSj = []
      this.handleQuery();
    },
    resetQueryParam() {
      this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          bjdh: undefined,
          khid: undefined,
          khname: undefined,
          bjdfj: undefined,
          bjdfjpdf: undefined,
          htje: undefined,
          khsh: undefined,
          wgdh: undefined,
          wgrq: undefined,
          zjfs: undefined,
          wgdfj: undefined,
          wgdfjpdf: undefined,
          xcrq: undefined,
          xcfzr: undefined,
          xcfzrname: undefined,
          xcry: undefined,
          xclx: undefined,
          sfsqdzd: undefined,
          sfgkhdzd: undefined,
          zzdy: undefined,
          yyjkh: undefined,
          sfkp: undefined,
          kpje: undefined,
          fph: undefined,
          kprq: undefined,
          tscl: undefined,
          wbqk: undefined,
          sfhk: undefined,
          hkje: undefined,
          hkrq: undefined,
          dzzh: undefined,
          ssgs: undefined,
          bz: undefined,
          params: {}
      }
      this.querySj = []
      this.queryWgSj = []
      this.ywdWs = []
      this.wgdWs = []
      this.sfhk = []
      this.rq = []
      this.xczt = []
      this.ssgs = []
      this.tscl = []
      this.sqdzd = []
      this.dzdsfgkh = []
      this.zzdy = []
      this.yyjkh = []
      this.yhsfqr = []
      this.sfkp = []
      this.xctzyh = []
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.type = 1
      this.open = true;
      this.title = "添加业务完工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getYwdwgd(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改业务完工单";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除业务完工单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delYwdwgd(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gd/ywdwgd/export', {
        ...this.queryParams
      }, `业务单_${new Date().getTime()}.xlsx`)
    },
    // 导出选择数据
    handleSelectExport() {
      const ids = this.ids;
      let name = this.getTodayDate()
      this.download('gd/ywdwgd/exportSelectData/' + ids, {
        ...this.queryParams
      }, `${name} 业务单_${new Date().getTime()}.xlsx`)
    },
    // 导出选择数据
    handleSelectKfp() {
      const ids = this.ids;
      if (ids.length === 0) {
        this.$message.error('请选择数据')
        return
      }
      const data = this.ywdwgdList.filter(item => ids.some(id => id === item.id))
      // 判断要导出的数据是否有：完工单
      const yws = []
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (item.wgdfj === '' || item.wgdfj === null) {  // 证书
          obj += "(报价单号为： " + item.bjdh + " 的数据未上传完工单),"
        }else {
          yws.push(item)
        }
      }
      if (obj.length > 200) {
        obj = obj.substring(0, 200) + "...，完工单未完善，将不进行导出，如想导出请先完善。"
      }
      if (yws.length === 0) {
        this.$message.error('请先完善 ' + obj)
        return
      }
      this.$modal.confirm("是否导出开票列表? " + obj).then(() => {
        let ids = yws.map(item => item.id).toString()
        handleKfp(ids, 'blob').then(res => {
          if (res !== null) {
            const binaryData = [];
            binaryData.push(res);
            let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
            const link = document.createElement('a');
            link.href = url
            link.download = this.getTodayDate() + "_开票信息.xlsx";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }else {
            this.$message.error("开票失败！")
          }
        })

      })
    },
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}${month}${day}`;
    },
    copyText(data) {
      const textarea = document.createElement('textarea');
      textarea.value = data;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        // 尝试执行复制操作
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("已复制！")
        } else {
          this.$message.error("复制失败！")
        }
      } catch (error) {
        this.$message.error("复制失败！")
      }
      document.body.removeChild(textarea);
    },
    resetData(){
      resetDatabase().then(res => {
        console.log("res", res)
      })
    },
    selectRq(item) {
      if (item.length > 0) {
        let hasZt = item.some(item => item === 'zt');
        let hasJt = item.some(item => item === 'jt');
        // ===== 获取昨天日期
        let date = new Date()
        const yesterday = new Date(date);
        yesterday.setDate(yesterday.getDate() - 1); // 减去一天得到昨天的日期
        let zt = this.formatDate(yesterday);
        // ==== 获取今天日期
        let jt = this.formatDate(date);
        // 判断昨天和今天是否已经勾选
        if (hasZt && hasJt) {
          this.queryParams.startCreateTime = zt + " 00:00:00"
          this.queryParams.endCreateTime = jt + " 23:59:59"
          // this.queryParams.startCreateTime = zt
          // this.queryParams.endCreateTime = jt
        }else if (hasZt) {
          // 如果只有昨天
          this.queryParams.startCreateTime = zt + " 00:00:00"
          this.queryParams.endCreateTime = zt + " 23:59:59"
          // this.queryParams.startCreateTime = zt
          // this.queryParams.endCreateTime = zt
        }else if (hasJt) {
          this.queryParams.startCreateTime = jt + " 00:00:00"
          this.queryParams.endCreateTime = jt + " 23:59:59"
          // this.queryParams.startCreateTime = jt
          // this.queryParams.endCreateTime = jt
        }
      }else {
        this.queryParams.startCreateTime = ""
        this.queryParams.endCreateTime = ""
      }
      console.log("this.queryParams", this.queryParams)
      this.getList()
    },
    selectDay(item) {
      // 1.昨天 2.今天 3.明天
      let date = new Date()
      if (item === 1) {
        const yesterday = new Date(date);
        yesterday.setDate(yesterday.getDate() - 1); // 减去一天得到昨天的日期
        let zt = this.formatDate(yesterday);
        // this.queryParams.startCreateTime = zt + " 00:00:00"
        // this.queryParams.endCreateTime = zt + " 23:59:59"
        this.queryParams.startCreateTime = zt
        this.queryParams.endCreateTime = zt
      }else if (item === 2){
        let jt = this.formatDate(date);
        // this.queryParams.startCreateTime = jt + " 00:00:00"
        // this.queryParams.endCreateTime = jt + " 23:59:59"
        this.queryParams.startCreateTime = jt
        this.queryParams.endCreateTime = jt
      }else if (item === 3) {
        const tomorrow = new Date(date);
        tomorrow.setDate(tomorrow.getDate() + 1); // 加上一天得到明天的日期
        let mt = this.formatDate(tomorrow);
        // this.queryParams.startCreateTime = mt + " 00:00:00"
        // this.queryParams.endCreateTime = mt + " 23:59:59"
        this.queryParams.startCreateTime = mt
        this.queryParams.endCreateTime = mt
      }
      this.getList()
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 修改状态
    handleZt(type, name) {
      const ids = this.ids;
      const data = this.ywdwgdList.filter(item => ids.some(id => id === item.id))
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (obj.length > 200) {
          obj += "..."
          break
        }else {
          if (i === data.length-1) {
            obj += "编号为：" +item.bjdh + " 客户为： " + item.khname
          }else {
            obj += "编号为：" +item.bjdh + " 客户为： " + item.khname + ", "
          }
        }
      }
      this.$modal.confirm('请确认是否要修改 ' + obj+' 业务单的'+ name + '的状态').then(() => {
        this.loading = true;
        handleZt(ids, type).then(res => {
          if (res.data) {
            this.$message.success("修改成功！")
          }else {
            this.$message.error("修改失败！")
          }
        })
      }).finally(() => {
        this.loading = false;
        this.getList();
      });
    }
  }
};
</script>
<style scoped>
.el-radio {
  margin-right: 0px;
}
.el-checkbox {
  margin-right: 0px;
}
</style>
